import axios from "axios"
import Vue from "vue"
import loginUtil from "./login"

if (process.env.MOCK) {
  axios.defaults.baseURL = "/api"
} else {
  axios.defaults.baseURL = process.env.VUE_APP_API_PATH
  // axios.defaults.baseURL = "http://api-fat.tsingyun.net";
  // axios.defaults.baseURL = "http://172.24.0.51:7002"; //沧州现场
}

const setHeaderToken = () => {
  axios.defaults.headers.common["Authorization"] = `Bearer ${loginUtil.getToken()}`
}

axios.interceptors.response.use(
  function(response) {
    if (response.config.url == "/authorization/validCode") {
      //图形验证码接口需要获取服务端自定义的请求头
      let mark = response.headers.mark
      localStorage.setItem("mark", mark)
      return response.data
    }
    if ("" + response.data.code === "0") {
      return response.data.data
    } else if ("" + response.data.code === "20004" || "" + response.data.code === "20005" || "" + response.data.code === "20006") {
      // debugger;
      //token失效的情况
      loginUtil.removeToken()
      location.reload()
      // } else if ("" + response.data.code === "30004") {
      //   // 当返回code为30004时不能删除，有用户或者菜单关联
      //   return Promise.reject(response.data);
    } else {
      let isJson, msg
      try {
        msg = JSON.parse(response.data.msg)
        isJson = true
      } catch (e) {
        msg = response.data.msg
        isJson = false
      }
      Vue.prototype.$notify.error({
        title: "错误",
        message: isJson ? msg[Object.keys(msg)[0]] : msg,
      })
      console.group("业务逻辑错误")
      console.warn(`请求接口：${response.config.url}`)
      if (response.config.params) {
        console.warn(`请求参数：${JSON.stringify(response.config.params)}`)
      }
      console.warn(`错误描述：${response.data.msg}`)
      console.warn(`错误码：${response.data.code}`)
      console.groupEnd()
      return Promise.reject(response.data)
    }
  },
  function(error) {
    // Do something with response error
    if (axios.isCancel(error)) {
      return Promise.reject(error)
    }
    let msg
    // console.log('error',error)
    switch (error.response.status) {
      case 401:
        loginUtil.removeToken()
        location.reload()
        msg = "未授权"
        break
      case 403:
        msg = "请求被屏蔽"
        break
      case 404:
        msg = "请求未找到"
        break
      case 405:
        msg = "请求不被允许"
        break
      case 500:
        msg = "服务器错误"
        break
      default:
        msg = "请求出错"
        break
    }
    Vue.prototype.$notify.error({
      title: "错误",
      message: msg,
    })
    return Promise.reject(error)
  }
)
export default axios
export { setHeaderToken }
